import 'package:flutter/material.dart';
import 'package:wms/utils/utils.dart';
import '/models/LoadTaskData.dart';
import 'package:flutter/services.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
import '../../services/api_service.dart';
import 'package:provider/provider.dart';
import '../../services/auth_service.dart';
import '../system/fontsize_provider.dart';
import '../../utils/message_box.dart';
import '../../utils/rangeInput_formatter.dart';
import '../../models/cycle_count_response.dart';

class CountScreen extends StatefulWidget {
  const CountScreen({super.key});

  @override
  _CountScreenState createState() => _CountScreenState();
}

class _CountScreenState extends State<CountScreen> with WidgetsBindingObserver {
  late LoadTaskData taskData;
  Map<String, dynamic>? selectedSkuItem;
  final TextEditingController locationController = TextEditingController();
  final TextEditingController skuController = TextEditingController();
  final TextEditingController quantityController = TextEditingController();
  final TextEditingController damagedquantityController = TextEditingController();
  
  // 仅保留输入框的焦点节点（SKU和Location后续设为不可请求焦点）
  final FocusNode _locationFocusNode = FocusNode(canRequestFocus: false);
  final FocusNode _skuFocusNode = FocusNode(canRequestFocus: false);
  final FocusNode _quantityFocusNode = FocusNode(canRequestFocus: true);
  final FocusNode _damagedQuantityFocusNode = FocusNode(canRequestFocus: true);
  
  // 键盘状态管理（新增Damaged Quantity状态变量）
  bool _quantityKeyboardVisible = false;
  bool _damagedKeyboardVisible = false; // 新增
  String? _currentFocusField;

  String? sku;
  String? oldsku;
  String? lpnNumber;
  String? shipmentCode;
  String? packKey;
  String? internalItemNumber;
  
  int? warehouseId;
  int? taskId;
  int? quantity = 0;
  String? location;
  bool buttonStatu = false;
  int? maxAllowedValue = 9999999;
  List<Map<String, dynamic>> availableSkus = [];
  double baseFontSize = 13;
  double listFontSize = 12;
  late double _fontScale;

  // 底部按钮区域高度
  static const double _buttonAreaHeight = 60;

  // Status下拉列表状态
  String selectedStatus = 'Normal';
  final List<String> statusOptions = ['Normal','Damaged','On Hold'];

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    _initFocusListeners();
    
    // 【修改1：页面初始化时调用_getCountTasks加载列表数据】
    _initCountData();
    
    // SKU输入框焦点监听器（因只读，仅保留选中文本逻辑）
    _skuFocusNode.addListener(() {
      if (_skuFocusNode.hasFocus && skuController.text.isNotEmpty) {
        WidgetsBinding.instance.addPostFrameCallback((_) {
          skuController.selection = TextSelection(
            baseOffset: 0,
            extentOffset: skuController.text.length,
          );
        });
      }
    });
  }

  // 【新增：初始化列表数据】
  void _initCountData() async {
    if (!mounted) return;
    try {
      final cycleResponse = await _getCountTasks();
      if (cycleResponse['code'] == 2000 && cycleResponse['data'] != null) {
        setState(() {
          // 仅保留列表显示+业务必要字段
            print('cycleResponse-----$cycleResponse');
          availableSkus = (cycleResponse['data'] as List).map((detail) => {
            'id': detail['id'] ?? 0,
            'itemNumber': detail['item_number'] ?? 'N/A', // 对应Item Number
            'locationNumber': detail['location'] ?? 'N/A', // 对应Location
            'quantity': detail['quantity'] ?? 0, // 对应Qty
            'packKey': detail['pack_key'] ?? '', // 提交API必要字段
            'internalItemNumber': detail['internal_item_number'] ?? '', // 提交API必要字段
          }).cast<Map<String, dynamic>>().toList();
        });
      }
    } catch (e) {
      MessageBox.showMessageBox(context, '初始化数据失败: $e', isError: true);
    }
  }

  // 初始化焦点监听（补充Damaged Quantity焦点监听）
  void _initFocusListeners() {
    // 原有Quantity焦点监听
    _quantityFocusNode.addListener(() {
      _handleFocusChange('quantity', _quantityFocusNode);
    });
    // 新增Damaged Quantity焦点监听
    _damagedQuantityFocusNode.addListener(() {
      _handleFocusChange('damaged quantity', _damagedQuantityFocusNode);
    });
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    if (state == AppLifecycleState.resumed && mounted) {
      _resetAllKeyboards();
    }
  }

  // 焦点变化处理（核心修复：获得焦点时主动触发键盘显示）
  void _handleFocusChange(String field, FocusNode node) {
    if (node.hasFocus) {
      if (_currentFocusField != null && _currentFocusField != field) {
        _hideKeyboardForField(_currentFocusField!); // 隐藏前一个输入框的键盘
      }
      _setCurrentFocusField(field);
      _showKeyboardForField(field); // 获得焦点时立即触发键盘显示
    } else if (_currentFocusField == field) {
      _hideKeyboardForField(field);
      _currentFocusField = null;
    }
  }

  // 键盘控制方法（补充Damaged Quantity处理）
  void _setCurrentFocusField(String field) => setState(() => _currentFocusField = field);
  
  // 核心修复：增加状态校验，确保键盘仅在需要时显示
  void _showKeyboard() async {
    if (_currentFocusField == null) return;
    try {
      await SystemChannels.textInput.invokeMethod('TextInput.show');
    } catch (e) {
      print('显示键盘失败: $e');
      // 失败重试一次
      await Future.delayed(const Duration(milliseconds: 50));
      await SystemChannels.textInput.invokeMethod('TextInput.show');
    }
  }
  
  Future<void> _hideKeyboard() async {
    try {
      await SystemChannels.textInput.invokeMethod('TextInput.hide');
      await Future.delayed(const Duration(milliseconds: 50));
      await SystemChannels.textInput.invokeMethod('TextInput.hide');
    } catch (e) {
      print('隐藏键盘失败: $e');
      await Future.delayed(const Duration(milliseconds: 100));
      await SystemChannels.textInput.invokeMethod('TextInput.hide');
    }
  }
  
  // 显示键盘（补充Damaged Quantity状态）
  void _showKeyboardForField(String field) {
    if (!mounted) return;
    setState(() {
      if (field == 'quantity') _quantityKeyboardVisible = true;
      if (field == 'damaged quantity') _damagedKeyboardVisible = true; // 新增
    });
    _showKeyboard(); // 触发系统键盘
  }
  
  // 隐藏键盘（补充Damaged Quantity状态）
  void _hideKeyboardForField(String field) {
    if (!mounted) return;
    setState(() {
      if (field == 'quantity') _quantityKeyboardVisible = false;
      if (field == 'damaged quantity') _damagedKeyboardVisible = false; // 新增
    });
    _hideKeyboard(); // 触发系统键盘隐藏
  }
  
  // 切换键盘（原逻辑已支持，无需修改）
  void _toggleKeyboardForField(String field) {
    if (field != 'quantity' && field != 'damaged quantity') return;
    if (_getKeyboardState(field)) {
      _hideKeyboardForField(field);
      _unfocusField(field);
    } else {
      _focusOnField(field, showKeyboard: true);
    }
  }
  
  // 聚焦方法（核心修复：延迟触发键盘，确保焦点稳定）
  void _focusOnField(String field, {required bool showKeyboard}) {
    FocusScope.of(context).unfocus(); // 先取消所有焦点
    if (!mounted) return;

    // 1. 请求目标输入框焦点
    if (field == 'quantity') {
      FocusScope.of(context).requestFocus(_quantityFocusNode);
    } else if (field == 'damaged quantity') {
      FocusScope.of(context).requestFocus(_damagedQuantityFocusNode);
    }

    // 2. 滚动到可见区域
    WidgetsBinding.instance.addPostFrameCallback((_) {
      final focusNode = field == 'quantity' ? _quantityFocusNode : _damagedQuantityFocusNode;
      if (focusNode.context != null) {
        Scrollable.ensureVisible(
          focusNode.context!,
          alignment: 0.4,
          duration: const Duration(milliseconds: 200),
        );
      }

      // 3. 延迟100ms触发键盘（核心修复：等待焦点稳定）
      if (showKeyboard && mounted) {
        Future.delayed(const Duration(milliseconds: 100), () {
          _showKeyboardForField(field);
        });
      } else if (mounted) {
        _hideKeyboardForField(field);
      }
    });
  }
  
  // 取消焦点（补充Damaged Quantity）
  void _unfocusField(String field) {
    if (field == 'quantity') _quantityFocusNode.unfocus();
    if (field == 'damaged quantity') _damagedQuantityFocusNode.unfocus(); // 新增
  }
  
  // 获取键盘状态（补充Damaged Quantity）
  bool _getKeyboardState(String field) {
    if (field == 'quantity') return _quantityKeyboardVisible;
    if (field == 'damaged quantity') return _damagedKeyboardVisible; // 新增
    return false;
  }
  
  // 重置所有键盘（补充Damaged Quantity）
  void _resetAllKeyboards() {
    if (_currentFocusField == null && !_quantityKeyboardVisible && !_damagedKeyboardVisible) return;
    setState(() {
      _quantityKeyboardVisible = false;
      _damagedKeyboardVisible = false; // 新增
      _currentFocusField = null;
    });
    FocusScope.of(context).unfocus();
    _hideKeyboard();
  }

  // 输入框点击处理（保持逻辑，确保点击时触发聚焦）
  void _onInputTap(TextEditingController controller, String fieldType) {
    if (controller.text.isNotEmpty) {
      controller.selection = TextSelection(
        baseOffset: 0,
        extentOffset: controller.text.length,
      );
    }
    if (fieldType == 'quantity' || fieldType == 'damaged quantity') {
      _focusOnField(fieldType, showKeyboard: true);
    }
  }

  _updateButtonStatu(){
    setState(() {
      // 【修改2：按钮启用条件增加Location校验（因Location需从列表选中）】
      buttonStatu = skuController.text.isNotEmpty && 
                   locationController.text.isNotEmpty && 
                   quantityController.text.isNotEmpty;
    });
  }

  // 选择SKU处理（【修改3：选中时自动填充Location输入框】）
  void _handleSkuSelection(Map<String, dynamic> skuItem) {
    setState(() {
      if (selectedSkuItem == skuItem) {
        // 取消选中：清空所有输入框
        selectedSkuItem = null;
        packKey = null;
        internalItemNumber = null;
        skuController.clear();
        locationController.clear();
        quantityController.clear();
        damagedquantityController.clear();
        buttonStatu = false;
        maxAllowedValue = 9999999;
        taskId = null;
        selectedStatus = 'Normal';
      } else {
        // 选中项：自动填充SKU、Location、Quantity
        selectedSkuItem = skuItem;
        skuController.text = skuItem['itemNumber'] ?? '';
        locationController.text = skuItem['locationNumber'] ?? ''; // 自动填Location
        quantityController.text = skuItem['quantity'].toString();
        // damagedquantityController.text = skuItem['damagedquantity'].toString();
        taskId = skuItem['id'];
        packKey = skuItem['packKey'];
        internalItemNumber = skuItem['internalItemNumber'];
        buttonStatu = true;
        selectedStatus = 'Normal';
        _focusOnField('quantity', showKeyboard: true); // 选中后聚焦Quantity
      }
    });
  }

  // 处理扫描输入（【修改4：SKU只读，屏蔽扫描输入逻辑】）
  void _handleScanInput(String value) async {
    MessageBox.showMessageBox(context, 'SKU需从列表选中，不可直接输入', isError: true);
  }

  // 处理扫描枪输入（【修改5：Location只读，屏蔽扫描输入逻辑】）
  _handleScanBarcode(String value) async{
    MessageBox.showMessageBox(context, 'Location需从列表选中，不可直接输入', isError: true);
  }

  // 调用接口获取SKU列表（保持原逻辑，修复字段映射）
  Future<Map<String,dynamic>> _getCountTasks() async {
    final String param = 'page=1&limit=100&operation_type=Cycle';
    final apiUrl = '${ApiService.baseURL}${ApiService.getMoveOrCountTasks}$param';
    
    final authService = Provider.of<AuthService>(context, listen: false);
    final accessToken = authService.accessToken;
    
    try {
      final response = await http.get(
        Uri.parse(apiUrl),
        headers: {
          'Authorization': 'JWT $accessToken',
          'x-warehouse-id': '$warehouseId',
          'x-timezone': 'America/Los_Angeles',
          'Content-Type':'application/json',
          'X-Client-Type':'app'
        },
      );
      print('apiUrl---:$apiUrl');
      
      if (response.statusCode == 200) {
        String responseBody = utf8.decode(response.bodyBytes);
        Map<String, dynamic> jsonData = json.decode(responseBody);
        print('jsonData---:$jsonData');
        return jsonData;
      } else if (response.statusCode == 401) {
        AuthService auth = AuthService();
        auth.logout(context);
        throw Exception('The session has expired, Please log in again.');
      } else {
        throw Exception('Server error: ${response.statusCode}');
      }
    } catch (e) {
      throw Exception('$e');
    }
  }

  // 提交处理（【修改6：提交后清空所有输入框+重新加载列表】）
  _submit() async{
    try{
      _resetAllKeyboards();
      
      // 验证Location（从列表选中，理论上不会空，保留校验）
      if (locationController.text.isEmpty) {
        MessageBox.showMessageBox(context, 'Please select from Items list.', isError: true);
        return;
      }
      
      // 验证数量
      quantity = int.tryParse(quantityController.text);
      if (quantity == null || quantity! < 0) {
        MessageBox.showMessageBox(context, 'Please enter a valid quantity.', isError: true);
        _focusOnField('quantity', showKeyboard: true);
        return;
      }

      // 调用调整接口
      final result = await _adjustment();
      if(result['code'] == 2000){
        MessageBox.showMessageBox(context, result['msg']);
        
        // 【关键：重新获取列表数据更新界面】
        _initCountData();
        
        // 【关键：清空所有输入框和状态】
        setState(() {
          selectedSkuItem = null;
          skuController.clear();
          locationController.clear();
          quantityController.clear();
          damagedquantityController.clear();
          buttonStatu = false;
          taskId = null;
          selectedStatus = 'Normal';
        });
      } 
    }catch(e){
      MessageBox.showMessageBox(context, e.toString(), isError: true);
    }
  }

  // 调整接口调用（修复字段映射：pack_key和internal_item_number）
  Future<Map<dynamic,dynamic>> _adjustment() async {
    final apiUrl = ApiService.baseURL + ApiService.cycleUpdate;
    final authService = Provider.of<AuthService>(context, listen: false);
    final accessToken = authService.accessToken;
    
    if (packKey == null || internalItemNumber == null) {
      throw Exception('Missing SKU information');
    }
    
    try {
      var requestBody = {
        'warehouse': warehouseId,
        'location': locationController.text.trim(),
        'pack_key': packKey!.trim(), // 对应返回数据的pack_key
        'internal_item_number': internalItemNumber!.trim(), // 对应返回数据的internal_item_number
        'quantity': quantity,
        'notes' :'',
        'damaged_quantity':damagedquantityController.text.isEmpty ? 0 : int.parse(damagedquantityController.text.trim()),
        // 'status': selectedStatus,
        'cycle_task_id':taskId
      };
      
      final response = await http.post(
        Uri.parse(apiUrl),
        headers: {
          'Authorization': 'JWT $accessToken',
          'x-warehouse-id': '$warehouseId',
          'x-timezone': 'America/Los_Angeles',
          'Content-Type':'application/json',
          'X-Client-Type':'app'
        },
        body: jsonEncode(requestBody),
      );
      
      print('apiUrl-111--:$apiUrl');
      print('requestBody---:$requestBody');
      
      if(response.statusCode == 200){
        String responseBody = utf8.decode(response.bodyBytes);
        Map<String, dynamic> jsonData = json.decode(responseBody);
        print('jsonData-_adjustment--:${jsonData}');
        
        if (jsonData['code'] == 2000) {
          return jsonData;
        }
        else if(jsonData['code'] == 401){
          AuthService auth = AuthService();
          auth.logout(context);
          throw Exception('The session has expired, Please log in again.');
        }
        else {
          throw Exception('${jsonData['msg']}');
        }
      }
      else{
        throw Exception('Server error: ${response.statusCode}');
      }
    } catch (e) {
      throw Exception('$e');
    }
  }

  // 构建输入框通用组件（保持逻辑，确保图标状态正确）
  Widget _buildKeyboardInput({
    required String fieldType,
    required TextEditingController controller,
    required FocusNode focusNode,
    required String label,
    TextInputType keyboardType = TextInputType.text,
    List<TextInputFormatter>? inputFormatters,
    Function(String)? onSubmitted,
    Function(String)? onChanged,
    bool isSmallScreen = false,
  }) {
    // 控制：SKU和Location只读，不显示键盘图标
    final bool isReadOnly = fieldType == 'sku' || fieldType == 'location';
    final bool showKeyboardIcon = (fieldType == 'quantity' || fieldType == 'damaged quantity');

    return Row(
      children: [
        SizedBox(
          width: isSmallScreen ? 80 : 100,
          child: Text(
            '$label:',
            style: TextStyle(
              fontWeight: FontWeight.bold,
              fontSize: baseFontSize * _fontScale
            ),
          ),
        ),
        const SizedBox(width: 10),
        Expanded(
          child: SizedBox(
            height: 30,
            child: TextField(
              controller: controller,
              focusNode: focusNode,
              keyboardType: keyboardType,
              inputFormatters: inputFormatters,
              readOnly: isReadOnly, // 关键：SKU和Location只读
              // 核心：确保可编辑输入框能触发系统键盘（显式设置）
              enableInteractiveSelection: !isReadOnly,
              decoration: InputDecoration(
                border: const OutlineInputBorder(),
                contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
                // 关键：仅Quantity和Damaged Quantity显示键盘图标，状态由_getKeyboardState控制
                suffixIcon: showKeyboardIcon 
                    ? IconButton(
                        icon: Icon(
                          _getKeyboardState(fieldType) ? Icons.keyboard_hide : Icons.keyboard,
                          color: const Color(0xFF008363),
                          size: isSmallScreen ? 18 : 20,
                        ),
                        onPressed: () => _toggleKeyboardForField(fieldType),
                        splashRadius: 20,
                        padding: const EdgeInsets.all(4),
                        constraints: const BoxConstraints.tightFor(width: 36, height: 36),
                      )
                    : null,
              ),
              style: TextStyle(fontSize: baseFontSize * _fontScale),
              textInputAction: TextInputAction.done,
              onSubmitted: onSubmitted,
              onChanged: onChanged,
              onTap: () => _onInputTap(controller, fieldType),
              // 失去焦点时隐藏键盘（点击输入框外区域触发）
              onTapOutside: (event) {
                if (showKeyboardIcon) {
                  _hideKeyboardForField(fieldType);
                  _unfocusField(fieldType);
                }
              },
            ),
          ),
        ),
      ],
    );
  }

  // Status下拉列表（保持原逻辑不变）
  Widget _buildStatusDropdown({required bool isSmallScreen}) {
  return Row(
    children: [
      SizedBox(
        width: isSmallScreen ? 80 : 100,
        child: Text(
          'Status:',
          style: TextStyle(
            fontWeight: FontWeight.bold,
            fontSize: baseFontSize * _fontScale
          ),
        ),
      ),
      const SizedBox(width: 10),
      Expanded(
        child: Container(
          height: 30,
          padding: const EdgeInsets.symmetric(horizontal: 0, vertical: 0),
          decoration: BoxDecoration(
            border: Border.all(
              color: Colors.grey.shade400,
              width: 1.0,
            ),
            borderRadius: BorderRadius.circular(4.0),
          ),
          child: DropdownButtonHideUnderline(
            child: DropdownButton<String>(
              value: selectedStatus,
              isExpanded: true,
              padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 0),
              items: statusOptions.map((String option) {
                return DropdownMenuItem<String>(
                  value: option,
                  child: Container(
                    width: double.infinity,
                    child: Text(
                      option,
                      style: TextStyle(
                        fontSize: baseFontSize * _fontScale,
                        color: Colors.black87,
                      ),
                      textAlign: TextAlign.left,
                    ),
                  ),
                );
              }).toList(),
              onChanged: (String? newValue) {
                if (newValue != null) {
                  setState(() {
                    selectedStatus = newValue;
                  });
                }
              },
              alignment: Alignment.centerLeft,
              menuMaxHeight: 200,
              style: TextStyle(
                fontSize: baseFontSize * _fontScale,
                color: Colors.black87,
              ),
            ),
          ),
        ),
      ),
    ],
  );
}

  @override
  Widget build(BuildContext context) {
    _fontScale = Provider.of<FontSizeProvider>(context).fontScale;
    final user = Provider.of<AuthService>(context).currentUser;
    warehouseId = user?.warehouse;
    final mediaQuery = MediaQuery.of(context);
    final isSmallScreen = mediaQuery.size.width < 360;
    final bottomInset = mediaQuery.viewInsets.bottom;

    return Scaffold(
      appBar: AppBar(
        title: Text('Count', style: TextStyle(fontSize: 18 * _fontScale)),
        automaticallyImplyLeading: false,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back, color: Colors.white),
          onPressed: () {
            _resetAllKeyboards();
            Navigator.pushNamed(context, '/inventory');
          },
        ),
        actions: [
          IconButton(
            icon: const Icon(Icons.home, color: Colors.white),
            onPressed: () {
              _resetAllKeyboards();
              Navigator.pushNamed(context, '/home');
            },
          ),
        ],
        backgroundColor: const Color(0xFF008363),
      ),
      resizeToAvoidBottomInset: true,
      body: Stack(
        children: [
          Positioned(
            top: 0,
            left: 0,
            right: 0,
            bottom: _buttonAreaHeight,
            child: Padding(
              padding: EdgeInsets.symmetric(horizontal: 32,vertical: 16),
              child: LayoutBuilder(
                builder: (context, constraints) {
                  return GestureDetector(
                    onTap: _resetAllKeyboards,
                    behavior: HitTestBehavior.translucent,
                    child: SingleChildScrollView(
                      padding: EdgeInsets.only(bottom: bottomInset > 0 ? bottomInset + 20 : 20),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.stretch,
                        children: [
                          // SKU列表标题
                          Text(
                            'Count Tasks:',
                            style: TextStyle(
                              fontWeight: FontWeight.bold,
                              fontSize: baseFontSize * _fontScale
                            ),
                          ),
                          
                          // 【修改8：列表仅显示Location、Item Number、Qty】
                          Container(
                            height: 200,
                            constraints: BoxConstraints(maxHeight: constraints.maxHeight * 0.5),
                            decoration: BoxDecoration(
                              border: Border.all(color: Colors.grey, width: 1.0),
                              borderRadius: BorderRadius.circular(4.0),
                            ),
                            child: ClipRRect(
                              borderRadius: BorderRadius.circular(4.0),
                              child: ListView.builder(
                                physics: const ClampingScrollPhysics(),
                                itemCount: availableSkus.length,
                                itemBuilder: (context, index) {
                                  final skuItem = availableSkus[index];
                                  final isSelected = selectedSkuItem == skuItem;
                                  
                                  return InkWell(
                                    onTap: () => _handleSkuSelection(skuItem),
                                    child: Container(
                                      margin: const EdgeInsets.symmetric(vertical: 2),
                                      decoration: BoxDecoration(
                                        border: Border.all(color: const Color.fromARGB(255, 169, 168, 168), width: 0.5),
                                        borderRadius: BorderRadius.circular(4.0),
                                        color: isSelected ? Colors.green[50] : null,
                                      ),
                                      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                                      // 横向布局：3列分别显示3个字段
                                      child: Row(
                                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                        children: [
                                          // 1. Location
                                          Expanded(
                                            flex: 1,
                                            child: Text(
                                              '${skuItem['locationNumber']}',
                                              style: TextStyle(
                                                fontSize: listFontSize * _fontScale,
                                                color: isSelected ? Colors.green : Colors.black87,
                                              ),
                                            ),
                                          ),
                                          // 2. Item Number
                                          Expanded(
                                            flex: 1,
                                            child: Text(
                                              '${skuItem['itemNumber']}',
                                              style: TextStyle(
                                                fontSize: listFontSize * _fontScale,
                                                color: isSelected ? Colors.green : Colors.black87,
                                              ),
                                            ),
                                          ),
                                          Expanded(
                                            flex: 1,
                                            child: Text(
                                              '${skuItem['internalItemNumber']}',
                                              style: TextStyle(
                                                fontSize: listFontSize * _fontScale,
                                                color: isSelected ? Colors.green : Colors.black87,
                                              ),
                                            ),
                                          ),
                                        ],
                                      ),
                                    ),
                                  );
                                },
                              ),
                            ),
                          ),
                          const SizedBox(height: 20),
                          
                          // SKU输入框（只读+无键盘）
                          _buildKeyboardInput(
                            fieldType: 'sku',
                            controller: skuController,
                            focusNode: _skuFocusNode,
                            label: 'SKU',
                            onSubmitted: _handleScanInput,
                            // 只读无需输入变化监听
                            isSmallScreen: isSmallScreen,
                          ),
                          const SizedBox(height: 16),
                          
                          // Location输入框（只读+无键盘）
                          _buildKeyboardInput(
                            fieldType: 'location',
                            controller: locationController,
                            focusNode: _locationFocusNode,
                            label: 'Location',
                            onSubmitted: _handleScanBarcode,
                            // 只读无需输入变化监听
                            isSmallScreen: isSmallScreen,
                          ),
                          const SizedBox(height: 16),
                          
                          // Quantity输入框（保留键盘）
                          _buildKeyboardInput(
                            fieldType: 'quantity',
                            controller: quantityController,
                            focusNode: _quantityFocusNode,
                            label: 'Quantity',
                            keyboardType: TextInputType.number,
                            inputFormatters: [
                              FilteringTextInputFormatter.digitsOnly,
                              RangeInputFormatter(maxAllowedValue!)
                            ],
                            onChanged: (_) => _updateButtonStatu(),
                            isSmallScreen: isSmallScreen,
                          ),
                          const SizedBox(height: 16),
                          // Damaged Quantity输入框（已配置正确fieldType，与Quantity一致）
                          _buildKeyboardInput(
                            fieldType: 'damaged quantity', // 关键：字段类型正确
                            controller: damagedquantityController,
                            focusNode: _damagedQuantityFocusNode,
                            label: 'Damaged Qty',
                            keyboardType: TextInputType.number,
                            inputFormatters: [
                              FilteringTextInputFormatter.digitsOnly,
                              RangeInputFormatter(maxAllowedValue!)
                            ],
                            onChanged: (_) => _updateButtonStatu(),
                            isSmallScreen: isSmallScreen,
                          ),
                          // const SizedBox(height: 16),
                          
                          // Status下拉列表（不变）
                          // _buildStatusDropdown(isSmallScreen: isSmallScreen),
                          const SizedBox(height: 20),
                        ],
                      ),
                    ),
                  );
                },
              ),
            ),
          ),
          
          // Submit按钮（不变）
          Positioned(
            bottom: 0,
            left: 0,
            right: 0,
            height: _buttonAreaHeight,
            child: Container(
              padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 32),
              color: Theme.of(context).scaffoldBackgroundColor,
              child: Center(
                child: SizedBox(
                  width: 240,
                  height: 40,
                  child: ElevatedButton(
                    onPressed: buttonStatu ? _submit : null,
                    style: ElevatedButton.styleFrom(
                      backgroundColor: const Color(0xFF008363),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(8.0),
                      ),
                    ),
                    child: Text(
                      'Submit',
                      style: TextStyle(
                        fontWeight: FontWeight.bold,
                        fontSize: baseFontSize * _fontScale,
                        color: Colors.white
                      ),
                    ),
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    
    // 移除焦点监听（补充Damaged Quantity）
    _quantityFocusNode.removeListener(() => _handleFocusChange('quantity', _quantityFocusNode));
    _damagedQuantityFocusNode.removeListener(() => _handleFocusChange('damaged quantity', _damagedQuantityFocusNode)); // 新增
    
    // 释放资源
    _locationFocusNode.dispose();
    _skuFocusNode.dispose();
    _quantityFocusNode.dispose();
    _damagedQuantityFocusNode.dispose();
    locationController.dispose();
    skuController.dispose();
    quantityController.dispose();
    damagedquantityController.dispose();
    
    super.dispose();
  }
}